from flask import jsonify, request
from app.api import api_bp
from app.core.rag_service import RAGService
from app.models.document import Document
from app import db

# 初始化 RAG 服务
rag_service = RAGService()


@api_bp.route('/hello', methods=['GET'])
def hello_world():
    """测试接口"""
    return jsonify({'message': 'Hello, RAG Backend!'})

@api_bp.route('/testError', methods=['GET'])
def test_error():
    """测试接口"""
    from flask import abort
    abort(404)


@api_bp.route('/documents', methods=['POST'])
def create_document():
    """创建新文档"""
    data = request.json
    
    if not data or 'content' not in data:
        return jsonify({'error': 'Content is required'}), 400
    
    try:
        document = Document(
            title=data.get('title', 'Untitled Document'),
            content=data['content'],
            doc_metadata=data.get('metadata', {})
        )
        
        db.session.add(document)
        db.session.commit()
        
        # 添加到 RAG 服务
        rag_service.add_document(document.id, document.content)
        
        return jsonify({
            'id': document.id,
            'title': document.title,
            'message': 'Document created successfully'
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@api_bp.route('/documents', methods=['GET'])
def get_documents():
    """获取所有文档列表"""
    try:
        documents = Document.query.all()
        return jsonify([{
            'id': doc.id,
            'title': doc.title,
            'created_at': doc.created_at.isoformat()
        } for doc in documents])
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@api_bp.route('/documents/<int:doc_id>', methods=['GET'])
def get_document(doc_id):
    """获取单个文档详情"""
    try:
        document = Document.query.get_or_404(doc_id)
        return jsonify({
            'id': document.id,
            'title': document.title,
            'content': document.content,
            'metadata': document.doc_metadata,
            'created_at': document.created_at.isoformat()
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@api_bp.route('/query', methods=['POST'])
def query_rag():
    """向 RAG 系统提问"""
    data = request.json
    
    if not data or 'query' not in data:
        return jsonify({'error': 'Query is required'}), 400
    
    try:
        result = rag_service.query(data['query'])
        return jsonify({
            'answer': result['answer'],
            'sources': result.get('sources', [])
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500